#include "stdafx.h"
#include "VSCtxMenuFixApp.h"

static INT_PTR AboutDlgInit(HWND, UINT, WPARAM, LPARAM);
static LPWSTR GetAppVersion();

INT_PTR CALLBACK AboutDlgProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
    switch (message)
    {
    case WM_INITDIALOG:
        return AboutDlgInit(hDlg, message, wParam, lParam);

    case WM_COMMAND:
        if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL)
        {
            EndDialog(hDlg, LOWORD(wParam));
            return (INT_PTR)TRUE;
        }
        break;
    }

    return (INT_PTR)FALSE;
}

static INT_PTR AboutDlgInit(HWND hDlg, UINT message, WPARAM wParam, LPARAM)
{
    SetDlgItemText(hDlg, IDC_APP_TITLE, CMyResources::GetAppTitle());

    CMyBuffer<WCHAR> version(GetAppVersion());

    if (!version.IsNull())
    {
        SetDlgItemText(hDlg, IDC_APP_VERSION, version.GetBuffer());
    }

    RECT rcDialog;
    RECT rcDesktop;

    GetWindowRect(hDlg, &rcDialog);
    int dlgWidth = rcDialog.right - rcDialog.left;
    int dlgHeight = rcDialog.bottom - rcDialog.top;

    GetWindowRect(GetDesktopWindow(), &rcDesktop);
    int dskWidth = rcDesktop.right - rcDesktop.left;
    int dskHeight = rcDesktop.bottom - rcDesktop.top;

    SetWindowPos(hDlg, HWND_TOP, rcDesktop.left + (dskWidth - dlgWidth) / 2, rcDesktop.top + (dskHeight - dlgHeight) / 2, 0, 0, SWP_NOSIZE);

    return (INT_PTR)TRUE;
}

static LPWSTR GetAppVersion()
{
    CMyBuffer<WCHAR> currentProcessFileName(GetCurrentProcessFileName());

    if (currentProcessFileName.IsNull())
    {
        return NULL;
    }

    DWORD dwHandle;
    DWORD dwSize = GetFileVersionInfoSize(currentProcessFileName.GetBuffer(), &dwHandle);
    if (!dwSize)
    {
        return NULL;
    }

    CMyBuffer<BYTE> versionInfo(dwSize);

    if (versionInfo.IsNull())
    {
        return NULL;
    }

    if (!GetFileVersionInfo(currentProcessFileName.GetBuffer(), 0, dwSize, versionInfo.GetBuffer()))
    {
        return NULL;
    }

    VS_FIXEDFILEINFO* ffi;
    UINT uLen;
    if (!VerQueryValue(versionInfo.GetBuffer(), L"\\", (LPVOID*)(&ffi), &uLen))
    {
        return NULL;
    }

    CMyBuffer<WCHAR> version(32);
    wsprintf(version.GetBuffer(), L"Version %d.%d.%d.%d", HIWORD(ffi->dwFileVersionMS), LOWORD(ffi->dwFileVersionMS), HIWORD(ffi->dwFileVersionLS), LOWORD(ffi->dwFileVersionLS));

    return version.Detach();
}
